import json
from typing import Dict, Any, Optional, List
from room_manager import room_manager
from services.deck_service import deck_service


class WSHandlers:
    """WebSocket消息处理器"""
    
    def __init__(self):
        pass
    
    def handle_sync_own_decks(self, room_id: str, player_id: str, decks: List[Dict[str, Any]]) -> Dict[str, Any]:
        """处理SYNC_OWN_DECKS消息：逐个校验并放入room_own_decks"""
        try:
            # 验证并设置玩家自定义卡组
            success = deck_service.set_player_own_decks(room_id, player_id, decks)
            
            if success:
                return {
                    "success": True,
                    "message": f"Synced {len(decks)} custom decks",
                    "deck_count": len(decks)
                }
            else:
                return {
                    "success": False,
                    "error": "Invalid deck format or validation failed"
                }
                
        except Exception as e:
            print(f"Error handling sync own decks: {e}")
            return {
                "success": False,
                "error": f"Sync failed: {str(e)}"
            }
    
    def get_available_decks_for_player(self, room_id: str, player_id: str) -> List[Dict[str, Any]]:
        """合并内置卡组与该玩家的自定义卡组，返回给main.py调用方"""
        return deck_service.get_available_decks_for_player(room_id, player_id)
    
    def resolve_selected_deck(self, room_id: str, player_id: str, deck_name: str) -> Optional[Dict[str, Any]]:
        """根据名称返回最终deck_json（优先找玩家自定义，否则按内置从文件读）"""
        return deck_service.resolve_selected_deck(room_id, player_id, deck_name)
    
    def handle_select_deck(self, room_id: str, player_id: str, deck_name: str) -> Dict[str, Any]:
        """处理SELECT_DECK消息"""
        try:
            # 获取游戏状态
            game_state = room_manager.get_game_state(room_id)
            if not game_state:
                return {
                    "success": False,
                    "error": "Game state not found"
                }
            
            # 解析选择的卡组
            deck_json = self.resolve_selected_deck(room_id, player_id, deck_name)
            if not deck_json:
                return {
                    "success": False,
                    "error": f"Deck '{deck_name}' not found or you don't have permission to use it"
                }
            
            # 调用游戏状态的select_deck方法
            result = game_state.select_deck(player_id, deck_name)
            
            # 如果双方都选择了卡组，需要特殊处理自定义卡组
            if result.get("success") and result.get("all_selected"):
                # 获取双方选择的卡组JSON
                # 注意：每个玩家只能选择自己的卡组，所以用各自的player_id查找
                player1_deck = self.resolve_selected_deck(room_id, game_state.player1_id, game_state.deck_selected[game_state.player1_id])
                player2_deck = self.resolve_selected_deck(room_id, game_state.player2_id, game_state.deck_selected[game_state.player2_id])
                
                # 检查是否都成功获取到卡组
                if not player1_deck or not player2_deck:
                    print(f"ERROR: Failed to resolve decks - player1: {bool(player1_deck)}, player2: {bool(player2_deck)}")
                    return {
                        "success": False,
                        "error": "Failed to resolve selected decks"
                    }
                
                # 使用自定义的初始化方法
                self._initialize_decks_with_json(game_state, {
                    game_state.player1_id: player1_deck,
                    game_state.player2_id: player2_deck
                })
            
            return result
            
        except Exception as e:
            print(f"Error handling select deck: {e}")
            return {
                "success": False,
                "error": f"Select deck failed: {str(e)}"
            }
    
    def _initialize_decks_with_json(self, game_state, player_deck_json: Dict[str, Dict[str, Any]]):
        """使用deck_json初始化游戏（支持自定义卡组）"""
        import random
        
        for player_id in game_state.players:
            deck_json = player_deck_json.get(player_id)
            if not deck_json:
                continue
            
            # 解析卡组配置
            game_state.draw_piles[player_id] = []
            for card_entry in deck_json.get("cards", []):
                card_id = card_entry.get("card_id")
                count = card_entry.get("count", 1)
                for _ in range(count):
                    game_state.draw_piles[player_id].append(card_id)
            
            random.shuffle(game_state.draw_piles[player_id])
        
        # 抽8张牌进入换牌阶段
        for player_id in game_state.players:
            game_state.mulligan_cards[player_id] = []
            for _ in range(8):
                if game_state.draw_piles[player_id]:
                    card_id = game_state.draw_piles[player_id].pop(0)
                    game_state.mulligan_cards[player_id].append(card_id)
        
        # 切换到换牌阶段
        game_state.game_phase = "MULLIGAN"
    
    def cleanup_room(self, room_id: str):
        """清理房间相关数据"""
        deck_service.clear_room_decks(room_id)


# 全局实例
ws_handlers = WSHandlers()
